﻿using System;
using AutoStopApp.Core;
using AutoStopData.BussinessLogic;

namespace AutoStopApp.Controls
{
    public partial class PasswordChange : AjaxUserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += PageLoad;
            btnSave.Click += btnSave_Click;
        }

        void PageLoad(object sender, EventArgs e)
        {
            AddAjaxSetting(btnSave, pnlFormData);
            if (!IsPostBack)
            {
                var currentSession = SessionProvider.CurrentSession;
                if (currentSession == null)
                {
                    lblValidationError.Text = "Nie ste prihlásený";
                }
                else
                {
                    txtMail.Text = currentSession.User.Mail;
                }
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            string message;
            var currentSession = SessionProvider.CurrentSession;
            if (currentSession == null)
            {
                message = "Nie ste prihlásený";
            }
            else
            {
                if (currentSession.User.Password != txtCurrentPassword.Text)
                {
                    message = "Nesprávne zadané aktuálne heslo";
                }
                else
                {
                    Users.ChangePassword(currentSession.User.UserId, txtPassword1.Text);
                    message = "Heslo bolo úspešne zmenené";
                    SessionProvider.CurrentSession.User = Users.GetByMail(currentSession.User.Mail);
                }
            }
            lblValidationError.Text = message;
        }
    }
}